package com.ztools.pc.util;

import com.alibaba.excel.EasyExcel;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: seeTools
 * @Date: 2023/6/22  16:41
 * @Version 1.0
 */
@Component
public class ExcelUtil {

    /**
     * 一页最大数据数量
     */
    public static final long SHEET_NUMBER = 50000L;

    /**
     * 屏蔽字段
     */
    public static final String[] FIELD_ARRAYS = {
            "creatorId", "createdDate", "modifierId",
            "modifierName", "modifiedDate", "active",
            "version"
    };

    /**
     * 导出
     *
     * @param response   response
     * @param sheetIndex sheet下标
     * @param dataList   数据
     * @param className  导出类
     * @param fileName   文件名称
     */
    public void exportExcel(HttpServletResponse response, int sheetIndex, List dataList, Class className, String fileName) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String excelName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + excelName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), className)
                    .excludeColumnFiledNames(Arrays.asList(FIELD_ARRAYS))
                    .sheet(sheetIndex, "sheet" + sheetIndex)
                    .doWrite(dataList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询分页页数
     *
     * @param sheetNumber 一页最大数据数量
     * @param count       数据总数量
     * @return 分页页数
     */
    public long getPageSize(long sheetNumber, long count) {
        long pageSize = count / sheetNumber;
        if (count % sheetNumber != 0) {
            pageSize += 1;
        }
        return pageSize;
    }
}
